﻿using fuzhu;
using LH.Model.PU;
using LH.Model.ST;
using LH.U8API.Bus;
using LKU8.shoukuan;
using RDIFramework.BizLogic;
using SqlSuarEntity;
using SqlSugar;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Reflection;
using U8COWeb;
using XXX.Bo.ViewModel;
using XXX.Common;
using XXX.Models;
using XXX.Models.AS;
using XXX.Models.MO;
using XXX.Models.WDFT;
using XXX.Models.XXXEntities;
using Yonyou.U8.BO;
using ZDEntity;
using static LH.Model.PU.API_BOM;

namespace XXX.Bo
{

    /// <summary>
    /// 盘古MES信息推送
    /// </summary>
    public static class ASService
    {
        

        /// <summary>
        /// 自由项插入bas_part 表
        /// </summary>
        /// <param name="cinvcode">存货编码</param>
        /// <param name="cfree1">自由项1 </param>
        /// <param name="tran">事务</param>
        /// <param name="iPartid0">新增是产生的partid</param>
        /// <returns></returns>
        static string InsertBasPart(string cinvcode, string cfree1, SqlTransaction tran, int iPartid0)
        {
            try
            {

                int iPartid = DbHelper.GetDbInt(DbHelper2.GetSingleWithTrans("select max(partid)+1 from bas_part", tran));

                string sQLString = string.Format(@" INSERT INTO [bas_part]
           ([PartId]
           ,[InvCode]
           ,[Free1]
           ,[Free2]
           ,[Free3]
           ,[Free4]
           ,[Free5]
           ,[Free6]
           ,[Free7]
           ,[Free8]
           ,[Free9]
           ,[Free10]
           ,[SafeQty]
           ,[MinQty]
           ,[MulQty]
           ,[FixQty]
           ,[bVirtual]
           ,[DrawCode]
           ,[LLC]
           ,[cBasEngineerFigNo]
           ,[fBasMaxSupply]
           ,[iSurenessType]
           ,[iDateType]
           ,[iDateSum]
           ,[iDynamicSurenessType]
           ,[iBestrowSum]
           ,[iPercentumSum]
           ,[RoundingFactor]
           ,[FreeStockFlag])
  select  '{0}'
           ,[InvCode]
           ,'{1}'
           ,[Free2]
           ,[Free3]
           ,[Free4]
           ,[Free5]
           ,[Free6]
           ,[Free7]
           ,[Free8]
           ,[Free9]
           ,[Free10]
           ,[SafeQty]
           ,[MinQty]
           ,[MulQty]
           ,[FixQty]
           ,0
           ,[DrawCode]
           ,[LLC]
           ,[cBasEngineerFigNo]
           ,[fBasMaxSupply]
           ,[iSurenessType]
           ,[iDateType]
           ,[iDateSum]
           ,[iDynamicSurenessType]
           ,[iBestrowSum]
           ,[iPercentumSum]
           ,[RoundingFactor]
           ,[FreeStockFlag] from bas_part where partid='{2}'", iPartid, cfree1, iPartid0);
                DbHelper2.ExecuteSqlWithTrans(sQLString, tran);
                return "ok";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }


        }

        /// <summary>
        /// 存货档案增加。 在调用前，检查是否有这个存货
        /// </summary>
        /// <param name="model">存货档案实体</param>
        /// <param name="cAccount">账套号，从中间库取连接字符串</param>
        /// <returns></returns>
        public static RetModelbool AS_Inventory_Modify(API_Inventory model, string cAccount)
        {
            try
            {
                string conStr = DBService.GetConStr(cAccount);
                if (string.IsNullOrEmpty(conStr))
                {
                    throw new Exception("未配置账套数据库");
                }


                RetModel retModel = new RetModel();

                //插入U8
                try
                {

                    //设置默认属性
                    API_Inventory inv = new API_Inventory();

                    string cRe = GetInfo.GetInventoryInfo(model, conStr, "1", out inv);


                    if (cRe != "ok")
                    {
                        throw new Exception(cRe);
                    }
                    string cerr;
                    string xmlconfig = XmlOperation.GetConfigXMLFromDB(cAccount).ToString();
                    if (!InventoryDALCO.ModifyInventory(inv, xmlconfig, out cerr))
                    {
                        throw new Exception(cerr);


                    }
                    return DBService.ReOKbool();

                }
                catch (Exception ex)
                {
                    return DBService.ReErrorbool(ex.Message);
                }

            }
            catch (Exception ex)
            {
                return DBService.ReErrorbool(ex.Message);
            }

        }

        ///// <summary>
        ///// 存货档案增加。 在调用前，检查是否有这个存货
        ///// </summary>
        ///// <param name="model">存货档案实体</param>
        ///// <param name="cAccount">账套号，从中间库取连接字符串</param>
        ///// <returns></returns>
        //public static RetModel<InvResult> AS_Inventory_Add(List<InventoryImport> model,string cAccount)
        //{
        //    try
        //    {
        //        string conStr = DBService.GetConStr(cAccount);
        //        if (string.IsNullOrEmpty(conStr))
        //        {
        //            throw new Exception("未配置账套数据库");
        //        }


        //        RetModel retModel = new RetModel();

        //        //插入U8
        //        try
        //        {

        //            List<InvResult> venResults = new List<InvResult>();
        //            for (int i = 0; i < model.Count; i++)
        //            {
        //                //设置默认属性
        //                Inventory inv = new Inventory();
        //                InvResult venResult = new InvResult();
        //                venResult.cInvCode = model[i].cInvCode;
        //                venResult.Result = "增加成功";
        //                //设置默认属性

        //                string cRe = GetInfo.GetInventoryInfo(model[i], conStr, "0", out inv);


        //                if (cRe != "ok")
        //                {
        //                    venResult.Result = cRe;
        //                }
        //                string cerr, cid;
        //                string xmlconfig = XmlOperation.GetConfigXMLFromDBIMS(cAccount).ToString();
        //                if (!ASDALCO.AddInventory(inv, xmlconfig, out cerr, out cid))
        //                {
        //                    venResult.Result = cerr;
        //                }
        //                venResults.Add(venResult);
        //            }
        //            return DBService.ReOK<InvResult>(venResults);
        //        }
        //        catch (Exception ex)
        //        {
        //            return DBService.ReError<InvResult>(ex.Message);
        //        }

        //    }
        //    catch (Exception ex)
        //    {
        //        return DBService.ReError<InvResult>(ex.Message);
        //    }

        //}


        ///// <summary>
        ///// 存货档案增加。 在调用前，检查是否有这个存货
        ///// </summary>
        ///// <param name="model">存货档案实体</param>
        ///// <param name="cAccount">账套号，从中间库取连接字符串</param>
        ///// <returns></returns>
        //public static RetModel<InvResult> AS_Inventory_Modify(List<InventoryImport> model, string cAccount)
        //{
        //    try
        //    {
        //        string conStr = DBService.GetConStr(cAccount);
        //        if (string.IsNullOrEmpty(conStr))
        //        {
        //            throw new Exception("未配置账套数据库");
        //        }


        //        RetModel retModel = new RetModel();

        //        //插入U8
        //        try
        //        {
        //            List<InvResult> venResults = new List<InvResult>();
        //            for (int i = 0; i < model.Count; i++)
        //            {
        //                //设置默认属性
        //                Inventory inv = new Inventory();
        //                InvResult venResult = new InvResult();
        //                venResult.cInvCode = model[i].cInvCode;
        //                venResult.Result = "修改成功";
        //                string cRe = GetInfo.GetInventoryInfo(model[i], conStr, "1", out inv);


        //                if (cRe != "ok")
        //                {
        //                    venResult.Result = cRe;
        //                }
        //                string cerr;
        //                string xmlconfig = XmlOperation.GetConfigXMLFromDBIMS(cAccount).ToString();
        //                if (!ASDALCO.ModifyInventory(inv, xmlconfig, out cerr))
        //                {
        //                    venResult.Result = cerr;
        //                }
        //                venResults.Add(venResult);
        //            }
        //            return DBService.ReOK<InvResult>(venResults);

        //        }
        //        catch (Exception ex)
        //        {
        //            return DBService.ReError<InvResult>(ex.Message);
        //        }

        //    }
        //    catch (Exception ex)
        //    {
        //        return DBService.ReError<InvResult>(ex.Message);
        //    }

        //}


        /// <summary>
        /// 客户档案增加 
        /// </summary>
        /// <param name="model">客户档案实体</param> 
        /// <returns></returns>
        public static RetModel<insertResult> AS_Customer_Add(AS_Customer model)
        {
            //全部正确返回200，其余都是300
            try
            {
                RetModel<insertResult> relst = new RetModel<insertResult>();
                relst.data = new List<insertResult>();
                int ierrcnt = 0;
                string sql = string.Format(@"select A.DBID, B.CSOURCE from ZDY_INTER_XIETONG a,zdy_inter_database b  where a.DBID = b.DBID
and a.CLX='OA客户档案' ");
                DataTable dtaccount = DbHelper2.ExecuteTable(sql, CanShu.conStrInter);
                for (int i = 0; i < dtaccount.Rows.Count; i++)
                {
                    string cAccount = DbHelper.GetDbString(dtaccount.Rows[i]["DBID"]);
                    string conStr = DbHelper.GetDbString(dtaccount.Rows[i]["CSOURCE"]);

                    string xmlconfig = XmlOperation.GetConfigXMLFromDB(cAccount).ToString();
                    //插入U8
                    insertResult invResult = new insertResult();
                    invResult.cVouCode = model.cCusCode;
                    invResult.cAccount = cAccount;

                    if (string.IsNullOrWhiteSpace(model.cInvoiceCompany))
                    {
                        model.cInvoiceCompany = model.cCusCode;
                    }
                    model.cCusCreditCompany = model.cCusCode;
                    model.cCusAddress = model.cCusOAddress;
                    //判断是否有这个客户
                    sql = string.Format("select count(*) from customer where cCusCode='{0}' ", model.cCusCode);
                    int iCnt = DbHelper.GetDbInt(DbHelper2.ExecuteScalar(sql, conStr));
                    if (iCnt == 0)
                    {
                        try
                        {
                            //取默认值合并
                            model = MergeEntity<AS_Customer>(model, CanShu.cusModel);
                            //读取业务员的部门
                            if (!string.IsNullOrWhiteSpace(model.cCusPPerson))
                            {
                                sql = string.Format("select cDepCode from Person where cPersonCode='{0}' ", model.cCusPPerson);
                                DataTable dtperson = DbHelper2.ExecuteTable(sql, conStr);
                                if (dtperson.Rows.Count == 0)
                                {
                                    throw new Exception("业务员编码不正确");
                                }
                                else
                                {
                                    model.cCusDepart = DbHelper.GetDbString(dtperson.Rows[0]["cDepCode"]);
                                }
                            }
                            string cerr, cid;
                            if (!CustomerDALCO.AddCustomer(model, xmlconfig, out cerr, out cid))
                            {
                                throw new Exception(cerr);
                            }
                            if (!string.IsNullOrWhiteSpace(model.cCusBank) && !string.IsNullOrWhiteSpace(model.cCusAccount))
                            {
                                sql = @"INSERT INTO CustomerBank(ccuscode, cbranch, caccountnum, caccountname, bdefault)
VALUES(@ccuscode, @cbranch, @caccountnum, @caccountname, 1)";
                                DbHelper2.ExecuteNonQuery(sql, new SqlParameter[]{
                             new SqlParameter("@ccuscode", model.cCusCode),
                             new SqlParameter("@cbranch",model.cCusBank),
                             new SqlParameter("@caccountnum",model.cCusAccount),
                             new SqlParameter("@caccountname",model.cCusName)
                    }, conStr);
                            }


                            invResult.cReCode = "200";
                            invResult.Result = "新增成功";
                        }
                        catch (Exception ex)
                        {
                            ierrcnt = 1;
                            invResult.cReCode = "300";
                            invResult.Result = "新增失败：" + ex.Message;
                        }
                        relst.data.Add(invResult);

                    }
                    else
                    {
                        //修改客户
                        try
                        {
                            string cerr, cid;
                            //读取业务员的部门
                            if (!string.IsNullOrWhiteSpace(model.cCusPPerson))
                            {
                                sql = string.Format("select cDepCode from Person where cPersonCode='{0}' ", model.cCusPPerson);
                                DataTable dtperson = DbHelper2.ExecuteTable(sql, conStr);
                                if (dtperson.Rows.Count == 0)
                                {
                                    throw new Exception("业务员编码不正确");
                                }
                                else
                                {
                                    model.cCusDepart = DbHelper.GetDbString(dtperson.Rows[0]["cDepCode"]);
                                }
                            }

                            //拼接字符串，获得更改的内容
                            string sqlupdate = UpdateEntitySQL<AS_Customer>(model, "cCusCode", model.cCusCode, "customer");

                            DbHelper2.ExecuteNonQuery(sqlupdate, conStr);


                            if (!string.IsNullOrWhiteSpace(model.cCusAccount) && !string.IsNullOrWhiteSpace(model.cCusBank))
                            {

                                //如果系统中存在，就不更新了，没有再更新
                                sql = String.Format(@"select  1 FROM CustomerBank WHERE cCusCode='{0}' and caccountnum='{1}'", model.cCusCode, model.cCusAccount);
                                DataTable dtcusadd = DbHelper2.ExecuteTable(sql, conStr);
                                if (dtcusadd.Rows.Count > 0)
                                {
                                    sql = string.Format(@"update CustomerBank set cbranch = N'{0}'  WHERE  ccuscode = N'{1}' and caccountnum='{2}' ", model.cCusBank, model.cCusCode, model.cCusAccount);
                                    DbHelper2.ExecuteNonQuery(sql, conStr);
                                }
                                else
                                {
                                    sql = @"INSERT INTO CustomerBank(ccuscode, cbranch, caccountnum, caccountname, bdefault)
VALUES(@ccuscode, @cbranch, @caccountnum, @caccountname, 1)";
                                    DbHelper2.ExecuteNonQuery(sql, new SqlParameter[]{
                             new SqlParameter("@ccuscode", model.cCusCode),
                             new SqlParameter("@cbranch",model.cCusBank),
                             new SqlParameter("@caccountnum",model.cCusAccount),
                             new SqlParameter("@caccountname",model.cCusName)
                    }, conStr);
                                }

                            }


                            //                            tran.Commit();
                            //                        }


                            invResult.cReCode = "200";
                            invResult.Result = "修改成功";
                        }
                        catch (Exception ex)
                        {
                            ierrcnt = 1;
                            invResult.cReCode = "300";
                            invResult.Result = "修改失败：" + ex.Message;
                        }
                        relst.data.Add(invResult);
                    }
                    //新增错误，删除导入的数据
                    if (ierrcnt > 0)
                    {
                        for (int j = 0; j < relst.data.Count; j++)
                        {
                            cAccount = DbHelper.GetDbString(dtaccount.Rows[j]["DBID"]);
                            conStr = DbHelper.GetDbString(dtaccount.Rows[j]["CSOURCE"]);
                            xmlconfig = XmlOperation.GetConfigXMLFromDB(cAccount).ToString();
                            string cerr = "";
                            //是否删除成功，不重要
                            CustomerDALCO.DelCustomer(model.cCusCode, xmlconfig, out cerr);
                        }

                        break;
                    }
                }
                if (ierrcnt == 0)
                {
                    relst.code = 200;
                    relst.message = "导入成功";
                }
                else
                {
                    relst.code = 300;
                    relst.message = "导入错误";
                }
                return relst;
            }
            catch (Exception ex)
            {
                return DBService.ReError<insertResult>(ex.Message);
            }

        }

        /// <summary>
        /// 供应商档案增加。 在调用前，检查是否有这个存货
        /// </summary>
        /// <param name="model">存货档案实体</param>
        /// <param name="cAccount">账套号，从中间库取连接字符串</param>
        /// <returns></returns>
        public static RetModelbool AS_Customer_Modify(AS_Customer model, string cAccount)
        {
            try
            {
                string conStr = DBService.GetConStr(cAccount);
                if (string.IsNullOrEmpty(conStr))
                {
                    throw new Exception("未配置账套数据库");
                }


                RetModel retModel = new RetModel();

                //插入U8
                try
                {
                    //LH.Model.PU.Pu_ArrivalVouch entity = new LH.Model.PU.Pu_ArrivalVouch(rdHead, bodies);

                    //设置默认属性
                    AS_Customer inv = new AS_Customer();
                    string cRe = GetInfo.GetCustomerInfo(model, conStr, "1", out inv);


                    if (cRe != "ok")
                    {
                        throw new Exception(cRe);
                    }
                    string cerr;
                    string xmlconfig = XmlOperation.GetConfigXMLFromDB(cAccount).ToString();
                    if (!CustomerDALCO.ModifyCustomer(inv, xmlconfig, out cerr))
                    {
                        throw new Exception(cerr);
                    }

                    return DBService.ReOKbool();
                }
                catch (Exception ex)
                {
                    return DBService.ReErrorbool(ex.Message);
                }

            }
            catch (Exception ex)
            {
                return DBService.ReErrorbool(ex.Message);
            }

        }

        /// <summary>
        /// 供应商档案增加
        /// </summary>
        /// <param name="model">存货档案实体</param> 
        /// <returns></returns>
        public static RetModel<insertResult> AS_Vendor_Add(AS_Vendor model)
        {
            //全部正确返回200，其余都是300
            try
            {

                RetModel<insertResult> relst = new RetModel<insertResult>();
                relst.data = new List<insertResult>();
                int ierrcnt = 0;
                string sql = string.Format(@"select A.DBID, B.CSOURCE from ZDY_INTER_XIETONG a,zdy_inter_database b  where a.DBID = b.DBID
and a.CLX='OA供应商档案' ");
                DataTable dtaccount = DbHelper2.ExecuteTable(sql, CanShu.conStrInter);
                for (int i = 0; i < dtaccount.Rows.Count; i++)
                {
                    string cAccount = DbHelper.GetDbString(dtaccount.Rows[i]["DBID"]);
                    string conStr = DbHelper.GetDbString(dtaccount.Rows[i]["CSOURCE"]);
                    string xmlconfig = XmlOperation.GetConfigXMLFromDB(cAccount).ToString();
                    //插入U8
                    insertResult invResult = new insertResult();
                    invResult.cVouCode = model.cVenCode;
                    invResult.cAccount = cAccount;
                    //判断是否有这个存货
                    sql = string.Format("select count(*) from vendor where cVenCode='{0}' ", model.cVenCode);
                    int iCnt = DbHelper.GetDbInt(DbHelper2.ExecuteScalar(sql, conStr));
                    if (iCnt == 0)
                    {
                        try
                        {
                            //取默认值合并
                            model = MergeEntity<AS_Vendor>(model, CanShu.venModel);
                            string cerr, cid;
                            if (!VendorDALCO.AddVendor(model, xmlconfig, out cerr, out cid))
                            {
                                throw new Exception(cerr);
                            }
                            invResult.cReCode = "200";
                            invResult.Result = "新增成功";
                        }
                        catch (Exception ex)
                        {
                            ierrcnt = 1;
                            invResult.cReCode = "300";
                            invResult.Result = "新增失败：" + ex.Message;
                        }
                        relst.data.Add(invResult);

                    }
                    else
                    {
                        //修改供应商
                        try
                        {

                            string cerr, cid;

                            ///
                            //sql = string.Format("select convert(char, convert(money, pubufts), 2) as ts  from inventory where cinvcode='{0}' ", model.cInvCode);
                            //string cufts = DbHelper.GetDbString(DbHelper2.ExecuteScalar(sql, conStr));
                            //model.pubufts = cufts;
                            if (!VendorDALCO.ModifyVendor(model, xmlconfig, out cerr))
                            {
                                throw new Exception(cerr);
                            }
                            invResult.cReCode = "200";
                            invResult.Result = "修改成功";
                        }
                        catch (Exception ex)
                        {
                            //ierrcnt = 1;
                            invResult.cReCode = "300";
                            invResult.Result = "修改失败：" + ex.Message;
                        }
                        relst.data.Add(invResult);

                    }
                    //新增错误，删除导入的数据
                    if (ierrcnt > 0)
                    {
                        for (int j = 0; j < relst.data.Count; j++)
                        {
                            cAccount = DbHelper.GetDbString(dtaccount.Rows[j]["DBID"]);
                            conStr = DbHelper.GetDbString(dtaccount.Rows[j]["CSOURCE"]);
                            xmlconfig = XmlOperation.GetConfigXMLFromDB(cAccount).ToString();
                            string cerr = "";
                            //是否删除成功，不重要
                            VendorDALCO.DelVendor(model.cVenCode, xmlconfig, out cerr);

                        }

                        break;
                    }
                }
                if (ierrcnt == 0)
                {
                    relst.code = 200;
                    relst.message = "导入成功";
                }
                else
                {
                    relst.code = 300;
                    relst.message = "导入错误";
                }
                return relst;
            }
            catch (Exception ex)
            {
                return DBService.ReError<insertResult>(ex.Message);
            }

        }

        /// <summary>
        /// 供应商档案增加。 在调用前，检查是否有这个存货
        /// </summary>
        /// <param name="model">存货档案实体</param>
        /// <param name="cAccount">账套号，从中间库取连接字符串</param>
        /// <returns></returns>
        public static RetModel<VenResult> AS_Vendor_Modify(List<AS_Vendor> model, string cAccount)
        {
            try
            {
                string conStr = DBService.GetConStr(cAccount);
                if (string.IsNullOrEmpty(conStr))
                {
                    throw new Exception("未配置账套数据库");
                }


                RetModel retModel = new RetModel();

                //插入U8
                try
                {
                    //LH.Model.PU.Pu_ArrivalVouch entity = new LH.Model.PU.Pu_ArrivalVouch(rdHead, bodies);
                    List<VenResult> venResults = new List<VenResult>();
                    //LH.Model.PU.Pu_ArrivalVouch entity = new LH.Model.PU.Pu_ArrivalVouch(rdHead, bodies);
                    for (int i = 0; i < model.Count; i++)
                    {
                        //设置默认属性
                        AS_Vendor inv = new AS_Vendor();
                        VenResult venResult = new VenResult();
                        venResult.cVenCode = model[i].cVenCode;
                        venResult.Result = "更改成功";
                        //设置默认属性 
                        string cRe = GetInfo.GetVendorInfo(model[i], conStr, "1", out inv);


                        if (cRe != "ok")
                        {
                            venResult.Result = cRe;
                        }
                        string cerr;
                        string xmlconfig = XmlOperation.GetConfigXMLFromDB(cAccount).ToString();
                        if (!VendorDALCO.ModifyVendor(inv, xmlconfig, out cerr))
                        {
                            venResult.Result = cerr;
                        }
                        venResults.Add(venResult);
                    }
                    return DBService.ReOK<VenResult>(venResults);
                }
                catch (Exception ex)
                {
                    return DBService.ReError<VenResult>(ex.Message);
                }

            }
            catch (Exception ex)
            {
                return DBService.ReError<VenResult>(ex.Message);
            }

        }


        /// <summary>
        /// BOM档案增加。 在调用前，检查是否有这个存货
        /// </summary>
        /// <param name="model">存货档案实体</param>
        /// <param name="cAccount">账套号，从中间库取连接字符串</param>
        /// <returns></returns>
        public static RetModel<BOMResult> AS_BOM_Add(List<ZDY_BOM_DAORU> model, string cAccount)
        {

            string conStr = DBService.GetConStr(cAccount);
            if (string.IsNullOrEmpty(conStr))
            {
                throw new Exception("未配置账套数据库");
            }


            RetModel retModel = new RetModel();

            //插入U8
            try
            {

                string taskcode = Guid.NewGuid().ToString();
                foreach (var item in model)
                {
                    item.Taskcode = taskcode;
                }
                //数据保存
                BOMResult bOMResult = new BOMResult();
                var x = SqlsugarHelper.Instance.Storageable(model).ToStorage(); //将数据进行分组 
                int returnInsertValue = x.AsInsertable.ExecuteCommand(); //执行插入 （可以换成雪花ID和自增）

                //执行BOM写入动作
                SqlsugarHelper.Instance.Ado.ExecuteCommand("exec ZDY_SP_BOM_Insert");
                string sql = string.Format(@"select parentcode as ParentCode,remark as Result from zdy_bom_daoru where taskcode='{0}'", taskcode);
                List<BOMResult> lstre = SqlsugarHelper.Instance.Ado.SqlQuery<BOMResult>(sql);

                return DBService.ReOK<BOMResult>(lstre);
            }
            catch (Exception ex)
            {
                return DBService.ReError<BOMResult>(ex.Message);
            }



        }
 

        

//        /// <summary>
//        /// 人员档案增加。 
//        /// </summary>
//        /// <param name="model">人员档案实体</param> 
//        /// <returns></returns>
//        public static RetModel<insertResult> AS_Person_Add(Person_New model)
//        {
//            //全部正确返回200，其余都是300
//            try
//            {
//                RetModel<insertResult> relst = new RetModel<insertResult>();
//                relst.data = new List<insertResult>();
//                int ierrcnt = 0;

//                //插入U8
//                insertResult invResult = new insertResult();
//                invResult.cVouCode = model.cPsn_Num;
//                //invResult.cAccount = cAccount;

//                //判断是否有这个人员
//                string sql = string.Format("select count(*) from hr_hi_person where cpsn_num='{0}' ", model.cPsn_Num);
//                int iCnt = DbHelper.GetDbInt(DbHelper2.ExecuteScalar(sql, CanShu.conStr));
//                if (iCnt == 0)
//                {
//                    SqlTransaction tran = DbHelper2.BeginTrans(CanShu.conStr);
//                    try
//                    {
//                        SqlParameter[] param = new SqlParameter[]{
//                new SqlParameter("@cPsn_Num",DbHelper.ToDbValue(model.cPsn_Num)),
//new SqlParameter("@cPsn_Name",DbHelper.ToDbValue(model.cPsn_Name)),
//new SqlParameter("@cDept_num",DbHelper.ToDbValue(model.cDept_num)),
//new SqlParameter("@rPersonType",DbHelper.ToDbValue(model.rPersonType)),
//new SqlParameter("@rSex",DbHelper.ToDbValue(model.rSex)),
//new SqlParameter("@vIDNo",DbHelper.ToDbValue(model.vIDNo)),
//new SqlParameter("@dEnterDate",DbHelper.ToDbValue(model.dEnterUnitDate)),
//new SqlParameter("@dEnterUnitDate",DbHelper.ToDbValue(model.dEnterUnitDate)),
//new SqlParameter("@bPsnPerson",DbHelper.ToDbValue(model.bPsnPerson)),
//new SqlParameter("@cPsnMobilePhone",DbHelper.ToDbValue(model.cPsnMobilePhone)),
//new SqlParameter("@cPsnFPhone",DbHelper.ToDbValue(model.cPsnFPhone)),
//new SqlParameter("@cPsnOPhone",DbHelper.ToDbValue(model.cPsnOPhone)),
//new SqlParameter("@cPsnInPhone",DbHelper.ToDbValue(model.cPsnInPhone)),
//new SqlParameter("@cPsnEmail",DbHelper.ToDbValue(model.cPsnEmail)),
//new SqlParameter("@cPsnPostAddr",DbHelper.ToDbValue(model.cPsnPostAddr)),
//new SqlParameter("@cPsnPostCode",DbHelper.ToDbValue(model.cPsnPostCode)),
//new SqlParameter("@cPsnFAddr",DbHelper.ToDbValue(model.cPsnFAddr)),
//new SqlParameter("@cPsnQQCode",DbHelper.ToDbValue(model.cPsnQQCode)),
//new SqlParameter("@dLeaveDate",DbHelper.ToDbValue(model.dLeaveDate)),
//new SqlParameter("@rEmployState",DbHelper.ToDbValue(model.rEmployState))

//          };
//                        sql = string.Format(@"INSERT INTO [dbo].[hr_hi_person]
//           ([cPsn_Num]
//           ,[cPsn_Name]
//           ,[cDept_num]
//           ,[rPersonType]
//           ,[rSex]  
//           ,[vIDNo] 
//           ,[dEnterDate],dEnterUnitDate
//           ,[bPsnPerson]
//           ,[cPsnMobilePhone]
//           ,[cPsnFPhone]
//           ,[cPsnOPhone]
//           ,[cPsnInPhone]
//           ,[cPsnEmail]
//           ,[cPsnPostAddr]
//           ,[cPsnPostCode]
//           ,[cPsnFAddr]
//           ,[cPsnQQCode]   
//           ,[pk_hr_hi_person]
//           ,[dLeaveDate]
//           ,[rEmployState]) values(@cPsn_Num
//           ,@cPsn_Name
//           ,@cDept_num
//           ,@rPersonType
//           ,@rSex  
//           ,@vIDNo 
//           ,@dEnterDate,@dEnterUnitDate
//           ,@bPsnPerson
//           ,@cPsnMobilePhone
//           ,@cPsnFPhone
//           ,@cPsnOPhone
//           ,@cPsnInPhone
//           ,@cPsnEmail
//           ,@cPsnPostAddr
//           ,@cPsnPostCode
//           ,@cPsnFAddr
//           ,@cPsnQQCode   
//           ,newid()
//           ,@dLeaveDate
//           ,@rEmployState)");
//                        DbHelper2.ExecuteSqlWithTrans(sql, param, CommandType.Text, tran);

//                        if (model.bPsnPerson == "1")
//                        {
//                            SqlParameter[] param2 = new SqlParameter[]{
//                new SqlParameter("@cPersonCode",DbHelper.ToDbValue(model.cPsn_Num)),
//new SqlParameter("@cPersonName",DbHelper.ToDbValue(model.cPsn_Name)),
//new SqlParameter("@cDepCode",DbHelper.ToDbValue(model.cDepcode)),
//new SqlParameter("@cPersonPhone",DbHelper.ToDbValue(model.cPsnMobilePhone)),
//new SqlParameter("@dPValidDate",DbHelper.ToDbValue(model.dEnterUnitDate)),
//new SqlParameter("@dPInValidDate",DbHelper.ToDbValue(model.dLeaveDate))
//                                };

//                            sql = string.Format(@"insert into person(cPersonCode, cPersonName, cDepCode, cPersonPhone,dPValidDate,dPInValidDate)
//values(@cPersonCode, @cPersonName, @cDepCode, @cPersonPhone,@dPValidDate,@dPInValidDate)");
//                            DbHelper2.ExecuteSqlWithTrans(sql, param2, CommandType.Text, tran);
//                        }
//                        DbHelper2.CommitTransAndCloseConnection(tran);
//                        invResult.cReCode = "200";
//                        invResult.Result = "新增成功";
//                    }
//                    catch (Exception ex)
//                    {
//                        DbHelper2.RollbackAndCloseConnection(tran);
//                        ierrcnt = 1;
//                        invResult.cReCode = "300";
//                        invResult.Result = "新增失败：" + ex.Message;

//                    }
//                    relst.data.Add(invResult);

//                }
//                else
//                {
//                    SqlTransaction tran = DbHelper2.BeginTrans(CanShu.conStr);
//                    //修改人员信息
//                    try
//                    {

//                        SqlParameter[] param = new SqlParameter[]{
//                new SqlParameter("@cPsn_Num",DbHelper.ToDbValue(model.cPsn_Num)),
//new SqlParameter("@cPsn_Name",DbHelper.ToDbValue(model.cPsn_Name)),
//new SqlParameter("@cDept_num",DbHelper.ToDbValue(model.cDept_num)),
//new SqlParameter("@rPersonType",DbHelper.ToDbValue(model.rPersonType)),
//new SqlParameter("@rSex",DbHelper.ToDbValue(model.rSex)),
//new SqlParameter("@vIDNo",DbHelper.ToDbValue(model.vIDNo)),
//new SqlParameter("@dEnterDate",DbHelper.ToDbValue(model.dEnterUnitDate)),
//new SqlParameter("@dEnterUnitDate",DbHelper.ToDbValue(model.dEnterUnitDate)),
//new SqlParameter("@bPsnPerson",DbHelper.ToDbValue(model.bPsnPerson)),
//new SqlParameter("@cPsnMobilePhone",DbHelper.ToDbValue(model.cPsnMobilePhone)),
//new SqlParameter("@cPsnFPhone",DbHelper.ToDbValue(model.cPsnFPhone)),
//new SqlParameter("@cPsnOPhone",DbHelper.ToDbValue(model.cPsnOPhone)),
//new SqlParameter("@cPsnInPhone",DbHelper.ToDbValue(model.cPsnInPhone)),
//new SqlParameter("@cPsnEmail",DbHelper.ToDbValue(model.cPsnEmail)),
//new SqlParameter("@cPsnPostAddr",DbHelper.ToDbValue(model.cPsnPostAddr)),
//new SqlParameter("@cPsnPostCode",DbHelper.ToDbValue(model.cPsnPostCode)),
//new SqlParameter("@cPsnFAddr",DbHelper.ToDbValue(model.cPsnFAddr)),
//new SqlParameter("@cPsnQQCode",DbHelper.ToDbValue(model.cPsnQQCode)),
//new SqlParameter("@dLeaveDate",DbHelper.ToDbValue(model.dLeaveDate)),
//new SqlParameter("@rEmployState",DbHelper.ToDbValue(model.rEmployState))

//          };
//                        sql = string.Format(@"update [dbo].[hr_hi_person]
//           set   [cPsn_Name]=@cPsn_Name
//           ,[cDept_num]=@cDept_num
//           ,[rPersonType]=@rPersonType
//           ,[rSex]  =@rSex
//           ,[vIDNo] =@vIDNo
//           ,[dEnterDate]=@dEnterDate
//,[dEnterUnitDate]=@dEnterUnitDate
//           ,[bPsnPerson]=@bPsnPerson
//           ,[cPsnMobilePhone]=@cPsnMobilePhone
//           ,[cPsnFPhone]=@cPsnFPhone
//           ,[cPsnOPhone]=@cPsnOPhone
//           ,[cPsnInPhone]=@cPsnInPhone
//           ,[cPsnEmail]=@cPsnEmail
//           ,[cPsnPostAddr]=@cPsnPostAddr
//           ,[cPsnPostCode]=@cPsnPostCode
//           ,[cPsnFAddr]=@cPsnFAddr
//           ,[cPsnQQCode] =@cPsnQQCode 
//           ,[dLeaveDate]=@dLeaveDate
//           ,[rEmployState] =@rEmployState where cpsn_num = @cpsn_num");
//                        DbHelper2.ExecuteSqlWithTrans(sql, param, CommandType.Text, tran);
//                        if (model.bPsnPerson == "1")
//                        {
//                            sql = string.Format(@"delete from  person where cPersonCode='{0}'", model.cPsn_Num);
//                            DbHelper2.ExecuteSqlWithTrans(sql, tran);

//                            SqlParameter[] param2 = new SqlParameter[]{
//                new SqlParameter("@cPersonCode",DbHelper.ToDbValue(model.cPsn_Num)),
//new SqlParameter("@cPersonName",DbHelper.ToDbValue(model.cPsn_Name)),
//new SqlParameter("@cDepCode",DbHelper.ToDbValue(model.cDepcode)),
//new SqlParameter("@cPersonPhone",DbHelper.ToDbValue(model.cPsnMobilePhone)),
//new SqlParameter("@dPValidDate",DbHelper.ToDbValue(model.dEnterUnitDate)),
//new SqlParameter("@dPInValidDate",DbHelper.ToDbValue(model.dLeaveDate))

//                                };

//                            sql = string.Format(@"insert into person(cPersonCode, cPersonName, cDepCode, cPersonPhone,dPValidDate,dPInValidDate)
//values(@cPersonCode, @cPersonName, @cDepCode, @cPersonPhone,@dPValidDate,@dPInValidDate)");
//                            DbHelper2.ExecuteSqlWithTrans(sql, param2, CommandType.Text, tran);

//                        }
//                        else
//                        {
//                            sql = string.Format(@"delete from  person where cPersonCode='{0}'", model.cPsn_Num);
//                            DbHelper2.ExecuteSqlWithTrans(sql, tran);

//                        }
//                        DbHelper2.CommitTransAndCloseConnection(tran);
//                        invResult.cReCode = "200";
//                        invResult.Result = "修改成功";
//                    }
//                    catch (Exception ex)
//                    {
//                        DbHelper2.RollbackAndCloseConnection(tran);
//                        ierrcnt = 1;
//                        invResult.cReCode = "300";
//                        invResult.Result = "修改失败：" + ex.Message;
//                    }
//                    relst.data.Add(invResult);
//                }
//                ////新增错误，删除导入的数据
//                //if (ierrcnt > 0)
//                //{
//                //    for (int j = 0; j < relst.data.Count; j++)
//                //    {
//                //        cAccount = DbHelper.GetDbString(dtaccount.Rows[j]["DBID"]);
//                //        conStr = DbHelper.GetDbString(dtaccount.Rows[j]["CSOURCE"]);
//                //        xmlconfig = XmlOperation.GetConfigXMLFromDBIMS(cAccount).ToString();
//                //        string cerr = "";
//                //        //是否删除成功，不重要
//                //        ASDALCO.DelDepartment(model.cDepCode, xmlconfig, out cerr);
//                //    }

//                //    break;
//                //}

//                if (ierrcnt == 0)
//                {
//                    relst.code = 200;
//                    relst.message = "导入成功";
//                }
//                else
//                {
//                    relst.code = 300;
//                    relst.message = "导入错误";
//                }
//                return relst;
//            }
//            catch (Exception ex)
//            {
//                return DBService.ReError<insertResult>(ex.Message);
//            }

//        }

//        /// <summary>
//        /// 存货档案增加。 在调用前，检查是否有这个存货
//        /// </summary>
//        /// <param name="model">存货档案实体</param>
//        /// <param name="cAccount">账套号，从中间库取连接字符串</param>
//        /// <returns></returns>
//        public static RetModelbool AS_Person_Modify(AS_Person model, string cAccount)
//        {
//            try
//            {
//                string conStr = DBService.GetConStr(cAccount);
//                if (string.IsNullOrEmpty(conStr))
//                {
//                    throw new Exception("未配置账套数据库");
//                }


//                RetModel retModel = new RetModel();

//                //插入U8
//                try
//                {

//                    string cerr, cid;
//                    string sql = string.Format(@"update hr_hi_person set cpsn_name=@cpsn_name,cDept_num=@cDept_num,rPersonType=@rPersonType,rSex=@rSex,
//dEnterDate=@dEnterDate,dEnterUnitDate=@dEnterDate,bPsnPerson=@bPsnPerson,cPsnMobilePhone=@cPsnMobilePhone,dLeaveDate=@dLeaveDate,rEmployState=@rEmployState
// where  cpsn_num = @cpsn_num
// ");
//                    SqlParameter[] param = new SqlParameter[]{
//                new SqlParameter("@cpsn_num",model.cPsn_Num),
//                       new SqlParameter("@cpsn_name",model.cPsn_Name),
//                        new SqlParameter("@cDept_num",model.cDept_num),
//                         new SqlParameter("@rPersonType",model.rPersonType),
//                          new SqlParameter("@rSex",model.rSex),
//                           new SqlParameter("@dEnterDate",model.dEnterUnitDate),
//                            new SqlParameter("@bPsnPerson",model.bPsnPerson),
//                             new SqlParameter("@cPsnMobilePhone",DbHelper.ToDbValue(model.cPsnMobilePhone)),
//                              new SqlParameter("@dLeaveDate",DbHelper.ToDbValue(model.dLeaveDate)),
//                               new SqlParameter("@rEmployState",DbHelper.ToDbValue(model.rEmployState)),

//          };
//                    DbHelper2.ExecuteNonQuery(sql, param, conStr);
//                    if (model.bPsnPerson == "1")
//                    {
//                        sql = string.Format(@"update person set cPersonName=@cPersonName,cDepCode=@cDepCode
//where cPersonCode = @cPersonCode)
// ");
//                        SqlParameter[] param2 = new SqlParameter[]{
//                new SqlParameter("@cPersonCode",model.cPsn_Num),
//                       new SqlParameter("@cPersonName",model.cPsn_Name),
//                        new SqlParameter("@cDepCode",model.cDept_num)

//          };
//                        DbHelper2.ExecuteNonQuery(sql, param, conStr);
//                    }

//                    return DBService.ReOKbool();

//                }
//                catch (Exception ex)
//                {
//                    return DBService.ReErrorbool(ex.Message);
//                }

//            }
//            catch (Exception ex)
//            {
//                return DBService.ReErrorbool(ex.Message);
//            }

//        }

         

        
        

       

        

        /// <summary>
        ///  传入的数据和模板进行合并，空值取模板
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t1">传入的实体</param>
        /// <param name="model">模板实体</param>
        /// <returns></returns>
        public static T MergeEntity<T>(T t1, T model)
        {
            Type type = t1.GetType();
            foreach (PropertyInfo p in type.GetProperties())
            {
                if (string.IsNullOrEmpty(DbHelper.GetDbString(p.GetValue(t1))) &&  !string.IsNullOrEmpty(DbHelper.GetDbString(p.GetValue(model))))
                {
                    p.SetValue(t1, p.GetValue(model));
                }
                else if (string.IsNullOrEmpty(DbHelper.GetDbString(p.GetValue(t1))))
                {
                    p.SetValue(t1, null);
                }
            }

            return t1;
        }

        /// <summary>
        ///  组合update 语句
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t1">传入的实体</param>
        /// <param name="cPKName">主键字段</param>
        /// <param name="cCode">主键值</param>
        /// <param name="cTableName">表名</param>
        /// <returns></returns>
        public static string UpdateEntitySQL<T>(T t1, string cPKName, string cCode, string cTableName)
        {
            Type type = t1.GetType();
            string[] sublist = { "bBatchCreate",
"bBatchProperty1",
"bBatchProperty10",
"bBatchProperty2",
"bBatchProperty3",
"bBatchProperty4",
"bBatchProperty5",
"bBatchProperty6",
"bBatchProperty7",
"bBatchProperty8",
"bBatchProperty9",
"bBondedInv",
"bCheckSubitemCost",
"bConsiderFreeStock",
"bControlFreeRange1",
"bControlFreeRange10",
"bControlFreeRange2",
"bControlFreeRange3",
"bControlFreeRange4",
"bControlFreeRange5",
"bControlFreeRange6",
"bControlFreeRange7",
"bControlFreeRange8",
"bControlFreeRange9",
"bCoupon",
"bFeatureMatch",
"bImport",
"bInByProCheck",
"bInvAsset",
"bInvKeyPart",
"bInvROHS",
"bIsAttachFile",
"bMaintenance",
"bOMPriceFree1",
"bOMPriceFree10",
"bOMPriceFree2",
"bOMPriceFree3",
"bOMPriceFree4",
"bOMPriceFree5",
"bOMPriceFree6",
"bOMPriceFree7",
"bOMPriceFree8",
"bOMPriceFree9",
"bPrjMat",
"bProcessMaterial",
"bProcessProduct",
"bProduceByFeatureAllocate",
"bPUQuota",
"bPurPriceFree1",
"bPurPriceFree10",
"bPurPriceFree2",
"bPurPriceFree3",
"bPurPriceFree4",
"bPurPriceFree5",
"bPurPriceFree6",
"bPurPriceFree7",
"bPurPriceFree8",
"bPurPriceFree9",
"bSalePriceFree1",
"bSalePriceFree10",
"bSalePriceFree2",
"bSalePriceFree3",
"bSalePriceFree4",
"bSalePriceFree5",
"bSalePriceFree6",
"bSalePriceFree7",
"bSalePriceFree8",
"bSalePriceFree9",
"bSCkeyProjections",
"bSrvProduct",
"bStoreCard",
"bSuitRetail",
"cInvAppDocNo",
"cInvSubCode",
"dInvCreateDatetime",
"fBuyExcess",
"fCurLFixManuCost",
"fCurLLaborCost",
"fCurLOMCost",
"fCurLVarManuCost",
"fInvCIQExch",
"fInvOutUpLimit",
"fMaterialCost",
"fNextLFixManuCost",
"fNextLLaborCost",
"fNextLOMCost",
"fNextLVarManuCost",
"fPrjMatLimit",
"fProcessCost",
"fRoundFactor",
"iAcceptDelayDays",
"iAcceptEarlyDays",
"iAvailabilityDate",
"iBestrowSum",
"iBOMExpandUnitType",
"iDateSum",
"iDateType",
"iDrawType",
"iDynamicSurenessType",
"iExpiratDateCalcu",
"iMaintenanceCycle",
"iMaintenanceCycleUnit",
"iMaterialsCycle",
"iNearRejectDays",
"iPercentumSum",
"iPlanCheckDay",
"iRequireTrackStyle",
"iSupplyPeriodType",
"iSurenessType",
"iTimeBucketId",
"iWarrantyPeriod",
"iWarrantyUnit"
};

            string[] sublistcus = {
            };
            string sql = "";
            foreach (PropertyInfo p in type.GetProperties())
            {
                if (p.GetValue(t1) != null && p.Name != cPKName)
                {
                    //在存货档案sub表里的字段
                    if (cTableName == "inventory" && sublist.Contains(p.Name))
                    {
                        continue;
                    }
                    //在
                    if (cTableName == "inventory_sub" && !sublist.Contains(p.Name))
                    {
                        continue;
                    }
                    if (p.Name.Contains("ufts"))
                    {
                        continue;
                    }
                    if (cTableName == "customer" && string.IsNullOrWhiteSpace(DbHelper.GetDbString(p.GetValue(t1))))
                    {
                        continue;
                    }
                    if (!string.IsNullOrEmpty(sql))
                    {
                        sql += string.Format(" ,{0}='{1}' ", p.Name, p.GetValue(t1));
                    }
                    else
                    {
                        sql = string.Format(" {0}='{1}' ", p.Name, p.GetValue(t1));
                    }

                }
            }
            string updatesql = string.Format(@"update {0} set {1} where {2}='{3}'", cTableName, sql, cPKName, cCode);
            return updatesql;
        }

        /// <summary>
        /// 万吉生产订单，新增
        /// </summary>
        /// <returns></returns>
        public static RetModel2 WanJi_MOMain_Add(WanJi_Morder_View_Lst model)
        {
            try
            {
                //检查订单号是否已导入
                MOrderVM mOrderVM = new MOrderVM();
                mOrderVM.conStr = CanShu.conStr;
                mOrderVM.cMoCode = model.vouList[0].cMoCode;
                mOrderVM.cMaker = model.cMaker;
                mOrderVM.cHandler = model.cMaker;
                string cMoid = "";
                if (mOrderVM.Exists(ref cMoid))
                {
                    return DBService.ReErrObject($"订单号{mOrderVM.cMoCode}已存在,不能重复导入;");
                }
                //销售订单号取传入的数据，不是+s了
                //string cSoCode = mOrderVM.cMoCode+"S";
                string cSoCode = model.vouList[0].cSoCode;
                SaleOrderVM saleOrderVM = new SaleOrderVM(new LH.Model.SA.SaleOrder.Head(),new List<LH.Model.SA.SaleOrder.Body>());
                saleOrderVM.conStr = CanShu.conStr;
                saleOrderVM.head.csocode = cSoCode;
                string soid = "";
                if (!saleOrderVM.Exists(ref soid))
                {
                    return DBService.ReErrObject($"销售订单号{cSoCode}不存在,请先导入销售订单;");
                }

                //从mrp计划中读取分解数据，写入生产订单。数量用计划数量. 取未删除的，未下订单的
                using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = CanShu.conStr,
                    DbType = SqlSugar.DbType.SqlServer,
                    IsAutoCloseConnection = true
                }))
                {
                    string sql = $@"select '1000000005' as MoTypeId,'1' as MoClass,
a.PartId as Partid,b.InvCode as cInvCode ,SoType,SoDid,SoCode as cSoCode,SoSeq,PlanCode,DueDate as dEndDate,StartDate as dBeginDate,
PlanQty-ISNULL(CrdQty,0) as iQuantity ,DemandId,'5' as WIPType,inv.cDefWareHouse as WhCode,inv.cInvDepCode as cDepCode
from mps_netdemand  a
inner join bas_part b on a.PartId = b.PartId 
inner join inventory inv on b.InvCode = inv.cInvCode
where  SoCode='{cSoCode}'  
and SupplyType=3  and delflag=0 and PlanQty-ISNULL(CrdQty,0)>0 ";
                    List<API_Morder.MorderDetail> morderDetails = db.Ado.SqlQuery<API_Morder.MorderDetail>(sql);
                    if (morderDetails.Count == 0)
                    {
                        return DBService.ReErrObject($"当前订单对应计划已全部下达;");
                    }
                    mOrderVM.ItemList  = morderDetails;

                } 
                    ////检查基础数据是否存在
                    //if (string.IsNullOrEmpty(model.vouList[0].cMoCode))
                    //{
                    //    throw new Exception("工单号不能为空");
                    //} 
                    //if (string.IsNullOrEmpty(DbHelper.GetDbString(model.vouList[0].dDate)))
                    //{
                    //    throw new Exception("生产日期不能为空");
                    //}
                    //if (string.IsNullOrEmpty(DbHelper.GetDbString(model.vouList[0].iQty)))
                    //{
                    //    throw new Exception("生产数量为空");
                    //}
                  
                #region 生成生产订单
               
                BOMVM bOMVM2 = new BOMVM();
                int i = 0;
                foreach (var morderDetail in mOrderVM.ItemList)
                {
               
                  
                 
                    morderDetail.SortSeq = (i + 1);
                    
                    morderDetail.BomId = bOMVM2.GetBomID(morderDetail.Partid);
                    
                    List<API_Morder.Material> lstbom = bOMVM2.GetBomOpComponent(morderDetail.BomId);
                    
                    for (int j = 0; j < lstbom.Count; j++)
                    {
                       lstbom[j].iRowNo = (j + 1);
                   } 
                    morderDetail.MaterialList = lstbom; 
                    i++;
                } 
                string strRes =  mOrderVM.InsertMo();
             
                if (strRes!="ok")
                {
                    return DBService.ReErrObject("新增生产订单失败：" + strRes);
                }
                #endregion 生成生产订单

                return DBService.ReOKObject("生产订单导入成功");
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }
        }


      
        
        private static void GetMaterialInfo(InventoryVM invm, BOMVM bOMVM2, API_Morder.MorderDetail morderDetail, API_Morder.Material material)
        {
            RetModel2 retModel3 = invm.GetPartidNoFree(material.cChildCode);
            if (retModel3.code == 200)
            {
                material.Componentid = DbHelper.GetDbInt(retModel3.data);
            }
            else
            {
                throw new Exception(material.cChildCode + retModel3.message);
            }
            material.WIPType = 3;
            material.OpComponentId = bOMVM2.GetOpcomponentID(morderDetail.BomId, material.Componentid);
            ////处理辅助计量单位,20241215 取消处理。wdft的直接写入
            //InvAuxCom invAuxCom3 = invm.GetAuxEntity(material.cChildCode);
            //if (invAuxCom3 != null)
            //{
            //    material.AuxUnitCode = invAuxCom3.cSTComUnitCode;
            //    material.ChangeRate = DbHelper.GetDbdecimal(invAuxCom3.iChangRate);
            //    if (material.ChangeRate != 0)
            //    {
            //        material.AuxQty = DbHelper.GetDbdecimal(material.dQty) / DbHelper.GetDbdecimal(invAuxCom3.iChangRate);
            //    }
            //    else
            //    {
            //        material.AuxUnitCode = null;
            //        material.AuxQty = null; 
            //    }

            //}
        }
        
        /// <summary>
        /// 威德封头，读取生产订单部门
        /// </summary>
        /// <param name="cItemCode"></param>
        /// <returns></returns>
        public static  string GetMoDepCode(string OpCode)
        {
            string sql = string.Format("select Define22 from sfc_operation where OpCode='{0}'", OpCode);
            return DbHelper.GetDbString(DbHelper2.ExecuteScalar(sql, CanShu.conStr));
        }

        /// <summary>
        /// 威德封头，读取工序名称
        /// </summary>
        /// <param name="cItemCode"></param>
        /// <returns></returns>
        public static Zdy_WDFT_OpDep GetOpEntity(string OpCode)
        {
            //20241218 更改，使用自定义的表
            using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = CanShu.conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            }))
            {

                Zdy_WDFT_OpDep zdy = db.Queryable<Zdy_WDFT_OpDep>()
                    .Where(x => x.cNo == OpCode).First();
 
                return zdy;
            }
          
        }
        /// <summary>
        /// 生成产成品入库单
        /// </summary>
        /// <param name="iid"></param>
        /// <returns></returns>
        public static RetModelbool ST_Rd10ByMO(YiJingRdrecord model)
        {
            try
            {
                string conStr = CanShu.conStr;

                if (model.itemList.Count == 0)
                {
                    return DBService.ReErrorbool("没有明细数据，无法保存");
                }
                if (string.IsNullOrEmpty(model.cHandler))
                {
                    return DBService.ReErrorbool("审核人为空，无法保存");
                }
                RetModel retModel = new RetModel();

                //插入U8
                try
                {

                    ST_Rdrecord10.Rd10Head rdHead = new ST_Rdrecord10.Rd10Head();

                    rdHead.cvouchtype = "10";

                    rdHead.cbustype = "成品入库";
                    rdHead.csource = "生产订单";
                    rdHead.cwhcode = model.cWhCode;
                    rdHead.ddate = model.dDate;
                    rdHead.ccode = model.cCode;
                    rdHead.cmaker = model.cMaker;
                    rdHead.cdepcode = model.cDepCode;
                    rdHead.cpersoncode = model.cPersonCode;
                    if (string.IsNullOrWhiteSpace(model.cRdCode))
                    {
                        rdHead.crdcode = CanShu.Rd10;
                    }
                    else
                    {
                        rdHead.crdcode = model.cRdCode;
                    }
                    rdHead.cmemo = model.cMemo;
                    //rdHead.idiscounttaxtype = "0";
                    //rdHead.bredvouch = "0";

                    rdHead.brdflag = "1";

                    rdHead.iPrintCount = "0";
                    rdHead.cdefine1 = model.cCode;   //避免系统编码，没有了传入的到货单的编码
                    rdHead.cdefine14 = model.QID;
                    rdHead.vt_id = "63";

                    List<LH.Model.ST.ST_Rdrecord10.Rd10Body> bodies = new List<LH.Model.ST.ST_Rdrecord10.Rd10Body>();
                    string sqlModid = @"select MoDId from mom_orderdetail where Free1 = '{0}' and MoId in (select MoId from mom_order where MoCode = '{1}')";
                    for (int i = 0; i < model.itemList.Count; i++)
                    {
                        LH.Model.ST.ST_Rdrecord10.Rd10Body body = new LH.Model.ST.ST_Rdrecord10.Rd10Body();
                        body.cinvcode = model.itemList[i].cInvCode;
                        //body.cfree1 = model.ItemList[i].cFree1;
                        body.iquantity = model.itemList[i].iQuantity;
                        //根据生产订单号，行号取imodid
                        body.cmocode = model.itemList[i].cMoCode;
                        body.imoseq = model.itemList[i].cMoRowNo;
                        //body.inum = model.ItemList[i].count;
                        body.editprop = "A";
                        body.irowno = model.itemList[i].iRowNo;
                        body.cdefine22 = model.itemList[i].cOpCode;
                        body.impoids = DbHelper.GetDbString(DbHelper2.ExecuteScalar(string.Format(sqlModid, body.cdefine22, body.cmocode), CanShu.conStr));
                        if (string.IsNullOrEmpty(body.impoids))
                        {
                            ExLog.WriteTxt(string.Format(sqlModid, body.cdefine22, body.cmocode));
                            return DBService.ReErrorbool(string.Format("工单号{0}工序编码{1}在U8内无对应的生产订单明细", body.cmocode, body.cdefine22));
                        }
                        bodies.Add(body);
                    }


                    string cRe = string.Empty;
                    string cerr, cid, ccode;

                    LH.Model.ST.ST_Rdrecord10 entity = new LH.Model.ST.ST_Rdrecord10(rdHead, bodies);
                    cRe = GetInfo.GetST10ByMOInfo(ref entity, conStr);
                    if (cRe != "ok")
                    {
                        return DBService.ReErrorbool(cRe);
                    }
                    if (!Rdrecord10DALCO.AddRdrecord10(entity, out cerr, out cid, out ccode))
                    {
                        return DBService.ReErrorbool(cerr);
                    }
                    string sql = string.Format(@"update RDRECORD10  set CHANDLER='{0}' where id='{1}'", model.cHandler, cid);
                    DbHelper2.ExecuteNonQuery(sql, conStr);

                    return DBService.ReOKbool();
                }
                catch (Exception ex)
                {
                    return DBService.ReErrorbool(ex.Message);
                }

            }
            catch (Exception ex)
            {
                return DBService.ReErrorbool(ex.Message);
            }




        }

        
    }

}
